/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { CommandFormFooter } from '@app-cad/common/components/command-form/footer';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { dataManager, docMgr } from '@app-cad/module';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { Button } from 'antd';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

type FormData = { surfaces: pickedFaceData[]; tol: number };

type Params = {
  surfaces: string[];
  tol: number;
};

// 曲面接合
function CommandFaceSew({ title, onClose, props }: CurvedCmdDialogParams) {
  const [formData, setFormData] = useState<FormData>({
    surfaces: [],
    tol: 0.1,
  });

  const { picker } = useTools();

  const selectAllSurface = () => {
    const result = docMgr.flatDocumentObjects
      .filter(({ isRecursiveVisible }) => isRecursiveVisible)
      .map(({ dxid }) => dataManager.getShapeData(dxid))
      .filter(Boolean)
      .flatMap(({ id, faces }) => faces?.map((v, i) => `${id}:f${i}`) ?? []);

    setFormData((prev) => ({
      ...prev,
      surfaces: result.map(
        (id) => picker.generatePickObjByPickID(id) as pickedFaceData,
      ),
    }));

    MessageTip.success(`已选择${result.length}个曲面`);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      return;
    }
    const params: Params = props.params;
    const { surfaces, tol } = params;

    await initEditDependency(surfaces);

    setFormData({
      surfaces: surfaces.map(
        (surface) => picker.generatePickObjByPickID(surface) as pickedFaceData,
      ),
      tol: tol,
    });
  }, []);

  const isFormDataValid = () => {
    return formData.surfaces.length > 1;
  };

  const execute = (preview: boolean = false) => {
    const { surfaces, tol } = formData;
    return confirmCommand(
      {
        type: 'Sew',
        a: {
          surfaces: surfaces.map((f) => f.meshId),
          tol,
        },
      },
      preview,
    );
  };

  const preview = async () => {
    clear();
    if (!isFormDataValid()) {
      return;
    }
    await execute(true);
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-face-sew', {
      commandName: 'CreateSurface',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      surfaces: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickFace,
        uniqueItems: true,
      },
      tol: {
        title: '误差',
        type: 'number',
        format: NumberInputFormat.Length,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        surfaces: {
          'ui:placeholder': '请输入接合曲面',
          'ui:autofocus': true,
        },
      }}
      noValidate
    >
      <Button
        type='primary'
        className='ml-auto block mr-5 mb-2 -mt-2'
        onClick={selectAllSurface}
      >
        选择全部可见曲面
      </Button>
      <CommandFormFooter
        onSubmit={checkAndFinishDraw}
        isSubmitLoading={isLoading}
        onClose={onClose}
        submitText='完成'
        isSubmitDisabled={!isFormDataValid()}
        isPreviewDisabled={!isFormDataValid()}
      />
    </PickableCommandForm>
  );
}

export const cmdFaceSew: CurvedBaseCommand = {
  id: 'CommandFaceSew',
  label: 'command.face-sew',
  icon: 'commands/curved/join',
  create: (label, onClose, props) => (
    <CommandFaceSew
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
